<template>
  <div>
    <a-card class="card-header">
      <a-form-model>
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- <a-button style="border: none;" icon="to-top">上传</a-button> -->
            <a-button style="border: none;" icon="file-add" @click="handleAdd"
              >新建</a-button
            >
            <a-button style="border: none;" icon="import" @click="handleImport"
              >导入</a-button
            >
            <a-button
              style="border: none;"
              icon="vertical-align-bottom"
              @click="download"
              >下载</a-button
            >
            <a-button style="border: none;" icon="copy" @click="copyProductPlan"
              >复制</a-button
            >
            <span style="margin: 0 10px;box-shadow: 0 2px 0 rgba(0, 0, 0, 0.015);padding: 7px;cursor: pointer;">
              <a-icon type="delete" />
              <a-popconfirm
                title="是否删除选中生产计划？"
                ok-text="是"
                cancel-text="否"
                @confirm="deleteProductPlan"
              >
                删除
              </a-popconfirm>
            </span>
            <a-button
              style="border: none;"
              icon="edit"
              @click="renameProductPlan"
              >重命名</a-button
            >
            <!-- <a-button style="border: none;" type="primary" ghost icon="read">详情</a-button> -->
          </a-col>
          <!-- <a-col :span="2" :offset="3">
            <a-button
              type="info"
              @click="handleGetAllPlan"
              style="margin-top: 1px;"
              >全部生产计划</a-button
            >
          </a-col> -->
          <a-col :span="4" :offset="6">
            <a-form-model-item
              label=""
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-model.trim="productPlan"
                placeholder="请输入计划单号"
                style="margin-top: -10px;width: 240px;"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="2" :offset="0">
            <a-button
              type="primary"
              @click="handleSearch"
              style="margin-top: 1px;"
              >查询</a-button
            >
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <!-- 表格区域 -->
    <a-card class="card-content">
      <div class="contetnBox">
        <!-- <a-row :gutter="24" class="headerBox">
          <a-col :span="20">
            <a-button type="primary" @click="handleAdd">添加生产计划</a-button>
          </a-col>
          <a-col :span="2" :offset="1">
            <a-button type="primary" @click="handleAllList('ProductPlanList')"
              >全部生产计划</a-button
            >
          </a-col>
        </a-row>
        <br /> -->
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          :rowKey="(record, index) => record.id"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :showHeader="showHeader"
        >
          <template slot="productPlan" slot-scope="text, record">
            <a-icon type="file-text" style="color: #4a90de;" />
            <a @click="handleProductionPlanDetail(record)">
              {{ text }}
            </a>
            <!-- <a-icon type="file-text" style="color: #4a90de;" /> -->
            <!-- <a-popconfirm
              title="确定删除该生产计划吗?"
              ok-text="是"
              cancel-text="否"
              @confirm="confirm()"
              @cancel=""
            >
              <a href="#">Delete</a>
            </a-popconfirm> -->
          </template>

          <!-- <template slot="action" slot-scope="text, record">
            <a @click="handleToDetail('/production/plan/detailv2', record)"
              >详情</a
            >
          </template> -->
        </a-table>
        <ChangeProductionPlan ref="modalForm" @ok="modalFormOk">
        </ChangeProductionPlan>
        <ProductionPlanDetailModal
          ref="planDetail"
          @ok="excelOk"
        ></ProductionPlanDetailModal>
      </div>
    </a-card>
  </div>
</template>

<script>
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";
import { planColumns } from "./components/tableConfig";
import ChangeProductionPlan from "./components/ChangeProductionPlan.vue";
import ProductionPlanDetailModal from "./components/ProductionPlanDetailModal.vue";
import api from "@/api/apiServer";
import XLSX from "xlsx";

export default {
  mixins: [tableMinxins],
  components: {
    ChangeProductionPlan,
    ProductionPlanDetailModal,
  },
  data() {
    return {
      productPlan: null,
      columns: planColumns,
      offset: [8, -4],
      pagination: {
        current: 1,
        pageNumber: 1,
        pageSize: 10,
        showQuickJumper: false,
        showSizeChanger: false,
        showTotal: (total) => `共 ${total} 条`,
        total: 0,
      },
      showHeader: true,
      selectedRowKeys: [],
    };
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  activated() {
    this.getList();
  },
  mounted() {
    this.getList();
  },
  methods: {
    async copyProductPlan() {
      if(this.selectedRowKeys.length<1){
        this.$message.error("请选择要复制的工单");
        return ;
      }
      let res = await api.CopyProductLine({ ids: this.selectedRowKeys });
      this.getList();
      this.selectedRowKeys = [];
      console.log(res);
    },
    //导入Execl
    handleImport() {
      let that = this;
      let execlInput = document.createElement("input");
      execlInput.type = "file";
      execlInput.click();
      execlInput.addEventListener("change", function(e) {
        that.load(execlInput);
      });
    },
    //读取本地execl函数
    load(inputEl) {
      let wb;
      let that = this;
      let tableData = [[]];
      let obj = inputEl;
      if (!obj.files) {
        return;
      }
      let f = obj.files[0];
      console.log(f);
      let reader = new FileReader();
      reader.onload = async function(e) {
        let data = e.target.result;
        wb = XLSX.read(data, {
          type: "binary", //以二进制的方式读取
          cellStyles: true,
        });
        console.log("wb: ", wb);
        //读取并设置表头
        let headReg = /^__EMPTY/;
        let headData = [];
        for (const key in XLSX.utils.sheet_to_json(
          wb.Sheets[wb.SheetNames[0]],
          {
            head: 0,
            defval: " ",
          }
        )[0]) {
          if (!headReg.test(key)) {
            headData.push(key.trim());
          }
        }
        let isAddPicCol = false;
        if (String(headData[3]).trim() != "工件图片") {
          headData.splice(3, 0, "工件图片");
          isAddPicCol = true;
        }
        XLSX.utils
          .sheet_to_json(wb.Sheets[wb.SheetNames[0]], { head: 0, defval: " " })
          .forEach((item) => {
            let itemArr = [];
            for (const key in item) {
              if (!headReg.test(key)) {
                itemArr.push(item[key]);
              }
            }
            if (isAddPicCol) {
              itemArr.splice(3, 0, "");
            }
            tableData.push(itemArr);
          });
        tableData.shift();
        console.log(tableData);
        that.$refs["planDetail"].planId = -2;
        that.$refs["planDetail"].title = `生产计划编号: ${f.name.split(".")[0]}`;
        that.$refs["planDetail"].importExecl = tableData;
        that.$refs["planDetail"].importSheetName = f.name.split(".")[0];
        that.$refs["planDetail"].modalAdd();
      };
      reader.readAsBinaryString(f);
    },
    excelOk() {
      this.getList();
    },
    async deleteProductPlan() {
      if(!this.selectedRowKeys.length){
        this.$message.error("请选择要删除的工单");
        return;
      }
      this.selectedRowKeys.forEach(async (item) => {
        await api.ProductPlanV2Delete({ id: item });
        this.$message.info("删除成功");
        this.getList();
      });
      this.selectedRowKeys = [];
    },
    renameProductPlan() {
      console.log(this.selectedRowKeys);
      if (this.selectedRowKeys.length != 1) {
        this.$message.error("请选择一个生产计划进行重命名");
      } else {
        this.$refs["modalForm"].modalAdd();
      }
    },
    handleGetAllPlan() {
      this.productPlan = null;
      this.getList();
    },
    download() {
      console.log(this.selectedRowKeys);
      if(this.selectedRowKeys.length<1){
        this.$message.error("请选择要下载的工单");
        return ;
      }
      for (let i = 0; i < this.selectedRowKeys.length; i++) {
        this.downLoadExecl(this.selectedRowKeys[i]);
      }
      this.selectedRowKeys = [];
    },
    async downLoadExecl(id) {
      //获取表头数据
      let headRes = await api.FindTableHead();
      let _head = JSON.parse(headRes.data.data);
      let headName = _head;
      let headData = [];
      for (let item in _head) {
        headData[~~item] = _head[item];
      }
      //获取表格数据
      let res = await api.ProductPlanV2GetDetail({ id: id });
      console.log(res);
      let excelData = JSON.parse(res.data.excelData);
      excelData.unshift(headName);
      let totalData = [];
      excelData.map((item) => {
        totalData.push(Object.values(item));
      });

      let tb = XLSX.utils.aoa_to_sheet(totalData);
      // aoa_to_sheet:将一个二维数组转成sheet，会自动处理number、string、boolean、date等类型数据；
      openDownloadDialog(
        sheet2blob(tb, "test"),
        `${res.data.productPlan}.xlsx`
      );
      // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
      function sheet2blob(sheet, sheetName) {
        sheetName = sheetName || "sheet1";
        var workbook = {
          SheetNames: [sheetName],
          Sheets: {},
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

        var wopts = {
          bookType: "xlsx", // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: "binary",
        };
        var wbout = XLSX.write(workbook, wopts);
        var blob = new Blob([s2ab(wbout)], {
          type: "application/octet-stream",
        }); // 字符串转ArrayBuffer
        function s2ab(s) {
          var buf = new ArrayBuffer(s.length);
          var view = new Uint8Array(buf);
          for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
          return buf;
        }
        return blob;
      }

      function openDownloadDialog(url, saveName) {
        if (typeof url == "object" && url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement("a");
        aLink.href = url;
        aLink.download = saveName || ""; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if (window.MouseEvent) event = new MouseEvent("click");
        else {
          event = document.createEvent("MouseEvents");
          event.initMouseEvent(
            "click",
            true,
            false,
            window,
            0,
            0,
            0,
            0,
            0,
            false,
            false,
            false,
            false,
            0,
            null
          );
        }
        aLink.dispatchEvent(event);
      }
    },
    async confirm(id) {
      let res = await api.ProductPlanV2Delete({ id: id });
    },
    start() {
      this.loading = true;
      // ajax request after empty completing
      setTimeout(() => {
        this.loading = false;
        this.selectedRowKeys = [];
      }, 1000);
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 获取列表数据
    async getList(arg) {
      this.loading = true;
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.pagination.current = 1;
      }
      console.log(this.pagination.pageNumber);
      const res = await api.ProductPlanV2GetList({
        productPlan: this.productPlan,
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.current,
      });
      this.tableData = res.data.data;
      this.pagination.total = res.data.total;
      this.loading = false;
    },
    handleTableChange(pagination) {
      console.log(pagination);
      this.pagination = pagination;
      this.getList();
    },
    // 新增
    handleAdd() {
      this.$refs["planDetail"].planId = -1;
      this.$refs["planDetail"].title = "生产计划编号: ";
      this.$refs["planDetail"].modalAdd();
    },
    // 详情
    handleProductionPlanDetail(record) {
      let { id, planNum } = record;
      this.$refs["planDetail"].planId = id;
      this.$refs["planDetail"].title = `生产计划编号:  ${planNum}`;
      this.$refs["planDetail"].modalAdd();
    },
    async modalFormOk(productPlan) {
      let res = await api.ProductPlanV2GetDetail({
        id: this.selectedRowKeys[0],
      });
      let params = {
        id: this.selectedRowKeys[0],
        productPlan: productPlan,
        excelData: res.data.excelData,
      };
      let changeRes = await api.ProductPlanV2Update(params);
      console.log(changeRes);
      this.getList();
    },
    handleToDetail(path, record) {
      let { id } = record;
      let query = { id };
      this.$router.push({ path, query });
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
  button {
    margin-right: 13px;
  }
}
.card-content {
  .contetnBox {
    min-height: 809px;
    // border: 1px solid #ebedf0;
    border-radius: 2px;
    padding: 20px 0;
    .headerBox {
      padding: 0 20px;
      border-top: 1px solid black;
    }
  }
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}

/deep/.ant-table-tbody tr:nth-child(2n) {
  background-color: #fafafa;
}
</style>
